/**
 * 
 */
package info.niwota.frames;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * @author qiangli
 * 
 */
public class ProgressDialog extends Dialog {

	public static ProgressDialog show(Context context, CharSequence title,
			CharSequence message) {
		return show(context, title, message, false);
	}

	public static ProgressDialog show(Context context, CharSequence title,
			CharSequence message, boolean indeterminate) {
		return show(context, title, message, indeterminate, false, null);
	}

	public static ProgressDialog show(Context context, CharSequence title,
			CharSequence message, boolean indeterminate, boolean cancelable) {
		return show(context, title, message, indeterminate, cancelable, null);
	}

	public static ProgressDialog show(Context context, CharSequence title,
			CharSequence message, boolean indeterminate, boolean cancelable,
			OnCancelListener cancelListener) {
		ProgressDialog dialog = new ProgressDialog(context);

		dialog.setTitle(title);
		dialog.setCancelable(cancelable);
		dialog.setOnCancelListener(cancelListener);

		//
		ProgressBar v = new ProgressBar(context);
		dialog.addContentView(v, new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		dialog.show();

		return dialog;
	}

	public ProgressDialog(Context context) {
		super(context, R.style.SpinDialog);
	}

	Runnable updateTimer = new Runnable() {
		public void run() {
			updateProgress();
		}
	};

	private final Handler handler = new Handler();

	private TextView textview;
	private ProgressBar progressbar;

	private long current;
	private long total;

	private long interval;

	private void updateProgress() {
		long c = current;

		String text = String.format("%s / %s K", c, total);

		textview.setText(text);
		progressbar.setProgress((int) (100 * c / total));

		if (isShowing()) {
			handler.postDelayed(updateTimer, interval);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		textview = (TextView) findViewById(R.id.progress_text);
		progressbar = (ProgressBar) findViewById(R.id.progress_bar);
	}

	public long getCurrent() {
		return current;
	}

	public void setCurrent(long current) {
		this.current = current;
	}

	public long getTotal() {
		return total;
	}

	public void setTotal(long total) {
		this.total = total;
	}

	public long getInterval() {
		return interval;
	}

	/**
	 * UI update frequency in milli seconds
	 * 
	 * @param interval
	 */
	public void setInterval(long interval) {
		this.interval = interval;
	}

}
